package com.yhny.lykj.yuhannongye.Adapter;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.longsichao.lscframe.net.HttpConnection;
import com.longsichao.lscframe.view.LSCToast;
import com.yhny.lykj.yuhannongye.R;
import com.yhny.lykj.yuhannongye.app.BaseRefreshListAdapter;
import com.yhny.lykj.yuhannongye.app.UserConfig;
import com.yhny.lykj.yuhannongye.model.AddressListModel;
import com.yhny.lykj.yuhannongye.model.BaseModel;
import com.yhny.lykj.yuhannongye.net.NetHelper;
import com.yhny.lykj.yuhannongye.tools.Tools;
import com.yhny.lykj.yuhannongye.ui.AddAddressActivity;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.Response;

/**
 * AddressListAdapter
 * 收获地址列表
 */
public class AddressListAdapter extends BaseRefreshListAdapter<AddressListAdapter.ViewHolder> {
    private List<AddressListModel.ListEntity> list;
    private OnItemClickListener listener = null;
    private int selectedPosition = -1;// 选中的位置
    private Context context;
    private ProgressDialog mProgressDialog;
    private int tag = 0;
    public AddressListAdapter(List<AddressListModel.ListEntity> list, Context context, int tag) {
        this.list = list;
        this.context = context;
        this.tag = tag;
    }

    @Override
    public void setOnItemClickListener(OnItemClickListener listener) {
        this.listener = listener;
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    @Override
    protected void onBindBaseViewHolder(ViewHolder holder, final int position) {
        final AddressListModel.ListEntity entity = list.get(position);
        holder.nameTv.setText("收货人："+entity.name);
        holder.infoView.setText(entity.adress);
        holder.phoneView.setText(entity.tel);
        final int pos = position;
        //删除
        holder.deleteTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showNormalDialog(pos);
            }
        });
        //编辑
        holder.editView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(context, AddAddressActivity.class);

                intent.putExtra(ADDRESS_ID,list.get(pos));
                intent.putExtra(ADDRESS_VIEW,ADDRESS_EDIT);
                context.startActivity(intent);
            }
        });

        if (tag!=FROM_TYPE_VIEW_CREAT_ORDER){
            holder.normalView.setText("选择默认地址");
            holder.normalView.setFocusable(true);
        }else{
            holder.normalView.setText("选择地址");
            holder.normalView.setFocusable(false);

        }

       if (entity.isdefault==0){
           Drawable img = holder.nameTv.getResources().getDrawable(R.drawable.ic_radio_noraml);
           holder.lineView.setVisibility(View.VISIBLE);
           img.setBounds(0, 0, img.getMinimumWidth(), img.getMinimumHeight());
           holder.normalView.setCompoundDrawables(img,null,null,null);
       }else{
           Drawable img = holder.nameTv.getResources().getDrawable(R.drawable.ic_radio_press);
           holder.lineView.setVisibility(View.GONE);
           img.setBounds(0, 0, img.getMinimumWidth(), img.getMinimumHeight());
           holder.normalView.setCompoundDrawables(img,null,null,null);
        }
        //默认地址
        holder.normalView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (tag!=FROM_TYPE_VIEW_CREAT_ORDER){
                    normalAddress(pos,list.get(pos).addressid);
                }
            }
        });

    }
    private void showNormalDialog(final int pos){
        /* @setIcon 设置对话框图标
         * @setTitle 设置对话框标题
         * @setMessage 设置对话框消息提示
         * setXXX方法返回Dialog对象，因此可以链式设置属性
         */
        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(context);
//        normalDialog.setIcon(R.drawable.icon_dialog);
        normalDialog.setTitle("删除收获地址");
        normalDialog.setMessage("是否删除收获地址?");
        normalDialog.setPositiveButton("是",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                        delAddress(pos,list.get(pos).addressid);
                    }
                });
        normalDialog.setNegativeButton("否",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                    }
                });
        // 显示
        normalDialog.show();
    }



    private void delAddress(final int pos, String aid){


        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        builder.addFormDataPart("action", "deladdress");
        builder.addFormDataPart("userid", UserConfig.getConfigUserId());
        builder.addFormDataPart("addressid", aid);
        Request request = new Request.Builder().url(NetHelper.User.delAddress(aid).getUrl()).post(builder.build()).build();
        HttpConnection.getHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                new Handler(Looper.getMainLooper()).post(new Runnable() {

                    @Override
                    public void run() {
                        LSCToast.show(context, "删除失败!");
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                final String string = response.body().string();

                new Handler(Looper.getMainLooper()).post(new Runnable() {

                    @Override
                    public void run() {
                        if (!Tools.isGoodJson(string)){
                            LSCToast.show(context, "删除失败!");
                        }else {
                            Gson gson = new GsonBuilder().serializeNulls().create();
                            BaseModel userInfo = gson.fromJson(string, BaseModel.class);
                            if (userInfo == null) {
                                LSCToast.show(context, "删除失败!");
                            } else {
                                list.remove(pos);
                                notifyDataSetChanged();
                                LSCToast.show(context, userInfo.msg);
                            }
                        }
                    }
                });
            }
        });
    }

    /**
     * 设置默认地址
     * @param pos
     * @param aid
     */
    private void normalAddress(final int pos, String aid){




            mProgressDialog = ProgressDialog.show(context, "", "加载中...");

            MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
            builder.addFormDataPart("action", "setAddress");
            builder.addFormDataPart("userid", UserConfig.getConfigUserId());
            builder.addFormDataPart("addressid", aid);
            Request request = new Request.Builder().url(NetHelper.User.normalAddress(aid).getUrl()).post(builder.build()).build();
            HttpConnection.getHttpClient().newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    new Handler(Looper.getMainLooper()).post(new Runnable() {

                        @Override
                        public void run() {
                            dismiss();
                            LSCToast.show(context, "设置失败!");
                        }
                    });
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {

                    final String string = response.body().string();

                    new Handler(Looper.getMainLooper()).post(new Runnable() {

                        @Override
                        public void run() {
                            if (!Tools.isGoodJson(string)) {
                                LSCToast.show(context, "设置失败!");
                            } else {
                                Gson gson = new GsonBuilder().serializeNulls().create();
                                BaseModel userInfo = gson.fromJson(string, BaseModel.class);
                                if (userInfo == null) {
                                    LSCToast.show(context, "设置失败!");
                                } else {
                                    for (int i = 0; i < list.size(); i++) {
                                        if (i == pos) {
                                            list.get(i).isdefault = 1;
                                        } else {
                                            list.get(i).isdefault = 0;
                                        }
                                    }
                                    notifyDataSetChanged();
                                    LSCToast.show(context, "设置成功！");
                                }
                            }
                            dismiss();
                        }
                    });
                }
            });

    }

    private void dismiss(){
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

    public void setSelectedPosition(int position) {
        selectedPosition = position;
    }
    @Override
    protected int getLayoutResId(int viewType) {
        return R.layout.item_address_list;
    }

    @Override
    protected ViewHolder onCreateBaseViewHolder(View itemView) {
        return new ViewHolder(itemView, listener);
    }


    public static class ViewHolder extends BaseRefreshListAdapter.ViewHolder {

        private TextView nameTv;
        private TextView infoView;
        private TextView deleteTv;
        private TextView phoneView;
        private TextView editView;
        private TextView normalView;
        private ImageView lineView;

        public ViewHolder(View itemView, OnItemClickListener listener) {
            super(itemView, listener);

            nameTv = (TextView) itemView.findViewById(R.id.address_name);
            phoneView = (TextView) itemView.findViewById(R.id.address_phone);
            infoView = (TextView) itemView.findViewById(R.id.address_info);
            deleteTv = (TextView) itemView.findViewById(R.id.address_delete);
            editView = (TextView) itemView.findViewById(R.id.address_edit);
            normalView = (TextView) itemView.findViewById(R.id.address_normal);
            lineView = (ImageView) itemView.findViewById(R.id.address_line);
        }

    }
}
